package wht.jly.forum.config.security.authenticationhandler;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lanyangji
 * @date 2019/3/2 20:31
 */
@Component("securityAuthenticationFailureHandler")
public class SecurityAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    /**
     * 登录错误信息
     */
    public static final String LOGIN_FAILURE_MESSAGE = "login_failure_message";
    /**
     * 用户登录信息
     */
    public static final String USER_LOGIN_INFO = "user_login_info";

    /**
     * 自定义认证失败处理逻辑
     *
     * @param request
     * @param response
     * @param exception
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        // 记录下日志
        logger.info("用户【" + ServletRequestUtils.getStringParameter(request, "username") + "】尝试登录失败.");

        // 获取用户登录信息，用以表单回显
        Map<String, String> userLoginInfo = getUserLoginInfo(request);
        // 将错误消息和登录信息放在session中
        request.getSession().setAttribute(LOGIN_FAILURE_MESSAGE, exception.getMessage());
        request.getSession().setAttribute(USER_LOGIN_INFO, userLoginInfo);

        super.onAuthenticationFailure(request, response, exception);
    }

    /**
     * 获取用户登录信息
     *
     * @param request
     * @return
     */
    private Map<String, String> getUserLoginInfo(HttpServletRequest request) throws ServletRequestBindingException {
        Map<String, String> map = new HashMap<>(3);

        String username = ServletRequestUtils.getStringParameter(request, "username");
        String password = ServletRequestUtils.getStringParameter(request, "password");
        map.put("username", username);
        map.put("password", password);

        return map;
    }
}
